<template>
    <div class="device-list">
        <div class="device-list-container flex-container">
            <el-row class="search-row">
                <el-col :span="24">
                    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                        <el-form-item label="医院">
                            <el-select v-model="searchForm.hospital" >
                                <el-option
                                        v-for="item in hospitalList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="配置的位置">
                            <el-select v-model="searchForm.location" >
                                <el-option
                                        v-for="item in searchTargetLocationList"
                                        :key="item.id"
                                        :label="item.value"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="配置的类型">
                            <el-select v-model="searchForm.type" >
                                <el-option
                                        v-for="item in searchTargetTypeList"
                                        :key="item.id"
                                        :label="item.value"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item class="pull-right">
                            <el-button type="primary" @click="clearSearchOption">清空</el-button>
                            <el-button type="success" @click="_configList()">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>

            <div class="device-list-table">

                <el-table :data="configList" border>

                    <el-table-column label="ID" prop="id"></el-table-column>
                    <el-table-column label="医院名称" prop="hospital_name"></el-table-column>
                    <el-table-column label="配置的位置">
                        <template slot-scope="scope">
                            {{ scope.row.target_location | configLocation }}
                        </template>
                    </el-table-column>
                    <el-table-column label="配置的类型">
                        <template slot-scope="scope">
                            {{ scope.row.target_type | configType }}
                        </template>
                    </el-table-column>
                    <el-table-column label="值">
                        <template slot-scope="scope">
                            <pre>{{ scope.row.value | strToJson}}</pre>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" fixed="right" width="200">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary outline"
                                       @click="handleSaveConfig(scope.row)">
                                编辑
                            </el-button>
                            <el-button size="mini" type="danger outline"
                                       @click="handleDelete(scope.$index, scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="flex-footer h-80">
                <div class="flex-footer-content">
                    <el-row>
                        <el-col :span="8" class="pt-6">
                            &nbsp;
                            <el-button type="success" @click="handleSaveConfig()">新增配置</el-button>
                        </el-col>
                        <el-col :span="16" class="text-right" v-if="total > 0">
                            <el-pagination
                                    @current-change="pageChange"
                                    :current-page="currentPage"
                                    :page-size="pageSize"
                                    layout="total, prev, pager, next, jumper"
                                    :total="total">
                            </el-pagination>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </div>

        <!--编辑弹窗-->
        <el-dialog :title="dialogTitle" custom-class="edit-dialog" :visible.sync="editModalVisible"
                   @close="handleCloseModal">
            <el-form :label-position="'left'" label-width="110px" ref="userForm" :model="configForm">
                <el-form-item label="医院">
                    <el-select v-model="configForm.hospital" >
                        <el-option
                                v-for="item in hospitalList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="配置的位置">
                    <el-select v-model="configForm.location" >
                        <el-option
                                v-for="item in searchTargetLocationList"
                                :key="item.id"
                                :label="item.value"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="配置的类型">
                    <el-select v-model="configForm.type" >
                        <el-option
                                v-for="item in searchTargetTypeList"
                                :key="item.id"
                                :label="item.value"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="轮播图">
                    <div v-for="(item, index) in configGoods" style="margin-bottom: 5px;">
                        <el-select v-model="configGoods[index].id" placeholder="请选择">
                            <el-option
                                    v-for="item in goodsList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>

                        <el-upload
                                class="avatar-uploader"
                                :action="Core.Const.NET.UPLOAD_FILE_URL"
                                :show-file-list="false"
                                :data="{index: index}"
                                @click.native="uploadIt(index)"
                                :on-success="handleImgUploadSuccess">
                            <img v-if="configGoods[index].imgUrl" :src="configGoods[index].imgUrl" class="avatar" style="width: 50px; height: 50px;">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <span style="display: inline-block; margin-right: 20px;">(351 * 165)</span>

                        <div class="action-btn add-btn" v-if="index <= 0" @click="addConfig"></div>
                        <div class="action-btn sub-btn" v-else @click="subConfig(index)"></div>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="success" @click="handleSave('configForm')">确认</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script type="text/ecmascript-6">

    import Core from 'core/core'

    export default {
        data() {
            return {
                Core: Core,
                editModalVisible: false,
				configForm: {
                    id: 0,
					hospital: "",
                    location: "",
                    type: "",
                    value: []
                },
				dialogTitle: "",
				coverImgUrl: "",

                hospitalList: [],
				configList: [],
				searchTargetLocationList: [
					{id: "", value: "全部"},
					//{id: 1, value: "首页"},
					{id: 2, value: "医疗器械"}
				],
				searchTargetTypeList: [
					{id: "", value: "全部"},
					//{id: 1, value: "医院"},
					{id: 2, value: "商品"}
				],
				searchForm: {
					hospital: "",
					location: "",
                    type: ""
				},

                // 分页配置
                currentPage: 1,
                total: 0,
                pageSize: 10,

				dialogHospitalId: 0,
                goodsList: [],
                configGoods: [{
                	id: '',
                    name: '',
                    img: '',
					imgUrl: '',
                    url: ''
                }],
				currentUploadIndex: 0
            }
        },

        mounted: function () {
        	this._hospitalList();
        	this._goodsList();
        },

		watch: {
			"configForm.hospital": {
				handler(newName, oldName) {
					this.dialogHospitalId = newName;
				},
				deep: true,
				immediate: true
			}
		},

		methods: {
			clearSearchOption() {
				this.searchForm.location = "";
				this.searchForm.type = "";

				this._configList();
			},

			addConfig () {
				this.configGoods.push({
					id: '',
					name: '',
					img: '',
                    imgUrl: '',
					url: ''
				})
            },

            subConfig (index) {
				this.configGoods.forEach((v, i) => {
					if (index == i) {
						this.configGoods.splice(i, 1)
                    }
                });
            },

			_hospitalList() {
				Core.Api.Hospital.allList()
					.then(res => {
						this.hospitalList = res.list;
						this.searchForm.hospital = this.hospitalList[0].id;
						return this._configList();
					})
			},

            _configList() {
				let hospitalId = this.searchForm.hospital;
				let location = this.searchForm.location || 0;
				let type = this.searchForm.type || 0;

				if (!hospitalId) {
					return;
                }

                Core.Api.Config.list(hospitalId, location, type, this.currentPage)
                    .then(res => {
                        this.configList = res.list;
                        this.total = res.count
                    })
                    .catch(err => {
                    })
            },

			_goodsList() {
				Core.Api.Goods.allList()
					.then(res => {
						this.goodsList = res.list;
					})
					.catch(err => {
					})
            },

            pageChange(val) {
                this.currentPage = val;
                this._configList();
            },

            handleSave(formName) {
				let value = [];

				for (let i=0; i < this.configGoods.length; i++) {
					for (let j=0; j < this.goodsList.length; j++) {
						if (this.configGoods[i].id == this.goodsList[j].id) {
							value.push({
								id: this.configGoods[i].id,
								name: this.goodsList[j].name,
								img: this.configGoods[i].img,
								imgUrl: this.configGoods[i].imgUrl,
								url: ''
							})
						}
					}
				}

				this.configForm.value = value;

				if (!this.configForm.hospital) {
					this.$message.error('请选择医院');
					return;
                }

				if (!this.configForm.location) {
					this.$message.error('请选择配置的位置');
					return;
				}

				if (!this.configForm.type) {
					this.$message.error('请选择配置的类型');
					return;
				}

                Core.Api.Config.save(
                    this.configForm.id,
                    this.configForm.hospital,
                    this.configForm.location,
                    this.configForm.type,
					JSON.stringify(this.configForm.value)
                ).then(res => {
					this.editModalVisible = false;
                    this.$message.success("更新成功")
                    this._configList()
                })
            },

            handleDelete(index, row) {
                this.$alert('确认删除吗?', {
                    confirmButtonText: '确定',
                    callback: action => {
                        if (action == 'confirm') {
                            Core.Api.Config.deleteConfig(row.id)
                                .then(res => {
                                    this.editModalVisible = false;
                                    this.$message.success("删除成功");
                                    this._configList();
                                })
                        }
                    }
                });
            },

            handleSaveConfig(item) {
                if (item) {
                    this.configForm = {
                        id: item.id,
						hospital: item.hospital_id,
						location: item.target_location,
						type: item.target_type,
						value: JSON.parse(item.value)
                    };
					this.configGoods = this.configForm.value;
                    this.dialogTitle = "配置编辑";
                } else {
					this.dialogTitle = "配置新增";
                }
                this.editModalVisible = true;
            },

            handleCloseModal() {
				this.configForm = {
					id: 0,
                    hospital: "",
                    location: "",
                    type: "",
                    value: []
				};
				this.configGoods = [{
					id: '',
					name: '',
					img: '',
                    imgUrl: '',
					url: ''
				}];
                this.currentUploadIndex = 0
            },

			uploadIt (index) {
                this.currentUploadIndex = index
            },

			handleImgUploadSuccess(res) {
                this.configGoods[this.currentUploadIndex].img = res.data.file_url;
				this.configGoods[this.currentUploadIndex].imgUrl = res.data.file_url;
			},
        }
    }
</script>

<style scoped lang="scss">
    .device-list {
        height: 100%;
        .device-list-container {
            height: 100%;
            .search-row {
                margin: 0;
                padding: 15px 30px;
                background: #fff;
                .el-form--inline .el-form-item {
                    margin-bottom: 0;
                }
                .el-form-item__label {
                    padding-right: 10px;
                    font-size: 12px;
                }
                .el-form-item__content {
                    .el-input {
                        width: 175px;
                    }
                }
            }

            .device-list-table {
                padding: 20px 0;
                background: #ffffff;
                position: relative;
                flex: 1;
                overflow: auto;
                .all-select-holder {
                    line-height: 30px;
                    position: absolute;
                    left: 10px;
                    z-index: 10;
                }
            }
            .flex-footer {
                border-top: 1px solid #E0E7EF;
            }
            .flex-footer.h-80 {
                height: 80px;
            }

        }

        a.success {
            display: inline-block;
            color: #fff;
            background-color: #03CC75;
            border-color: #03CC75;
            line-height: 1;
            white-space: nowrap;
            cursor: pointer;
            -webkit-appearance: none;
            text-align: center;
            box-sizing: border-box;
            outline: none;
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            padding: 7px 16px;
            font-size: 12px;
            border-radius: 4px;
            margin: 0 10px;
        }

        .upload-device {
            display: inline-block;
        }
    }

    .avatar-uploader {
        margin: 0 6px 0 20px;
        display: inline-block;
        height: 52px;
        vertical-align: middle;
    }

    .action-btn {
        display: inline-block;
        vertical-align: middle;
        width: 30px;
        height: 30px;
        &.add-btn {
            background: url("../../assets/img/icon/icon-add.png") no-repeat center center;
            background-size: 30px 30px;
        }
        &.sub-btn {
            background: url("../../assets/img/icon/icon-sub.png") no-repeat center center;
            background-size: 30px 30px;
        }
    }
</style>
